var MessageList = {
    init: function () {
        $$('.msg').each(MessageList.setupAccordion);

        $$('.msg .discard input').filter(function(x) { return x.type == 'image'; }).each(MessageList.setupDiscard);
    },

    setupAccordion: function (el) {
        var pre = el.select('.body')[0];
        if (!el.select('h2').length)
            pre.hide();

//        el.setStyle({cursor: 'pointer'});

        el.pre = pre;
        el.observe('click', MessageList.toggle.bindAsEventListener(el));
    },

    toggle: function (event) {
        var t = event.element()
        if (t.nodeName.toLowerCase() == 'a' || t.up('a') || t.up('form')) return;
        Effect.toggle(this.pre, 'blind', {duration: '0.3'});
    },

    setupDiscard: function (el) {
        el.observe('click', function (event) {
            event.stop();
            var div = el.up('div.msg');
            Effect.Fade(div, {to: 0.00001}); 
            Effect.BlindUp(div, {duration: 0.3, queue: 'end'}); 

            MessageList.decrementPager();

            var form = el.up('form');
            new Ajax.Request(form.action, {
                method: 'post',
                parameters: form.serialize(true)
            });

        }.bindAsEventListener(el));
    },

    decrementPager: function () {
        $$('.pager strong').each(function (p) {
            var match = /Showing (\d+)-(\d+) of (\d+)/.exec(p.innerHTML);
            if (match) {
                var of = parseInt(match[3], 10) - 1;
                if (match[2] == match[1]) {
                    p.update('Showing none of ' + of);
                } else {
                    var end = parseInt(match[2], 10) - 1;
                    p.update('Showing ' + match[1] + '-' + end + ' of ' + of);
                }
            }
        });
    }
};

Event.observe(document, 'dom:loaded', MessageList.init);
